package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.util.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "UserController", value = "/user/*")
public class UserController extends HttpServlet
{

    UserService userService = BeanFactroy.createBean(UserService.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String path = request.getPathInfo();

        if (path!=null) {
            if ("/queryUserById".equals(path)) {
                queryUserById(request, response);
            }else if ("/queryUserByUsername".equals(path)) {
                queryUserByUsername(request, response);
            }else if ("/loginUser".equals(path)) {
                loginUser(request, response);
            }else if ("/registerUser".equals(path)) {
                registerUser(request, response);
            }else if ("/updateUserById".equals(path)) {
                updateUserById(request, response);
            }else if ("/queryAllWorkByUserId".equals(path)) {
                queryAllWorkByUserId(request, response);
            }else if ("/searchAllWorkByWord".equals(path)) {
                searchAllWorkByWord(request, response);
            }else if ("/loginUserByMsg".equals(path)) {
                loginUserByMsg(request, response);
            }else if ("/getLoginMsg".equals(path)) {
                getLoginMsg(request, response);
            }
        }
    }
    //获取短信验证码并存到session
    private void getLoginMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int vcode = ValidateCodeUtils.generateValidateCode(4);
        System.out.println(vcode);
        String code = vcode+"";
        //SMSUtils.sendMessage("阿里云短信测试","SMS_154950909","19994587757",code+"");

        request.getSession().setAttribute("MSG_CODE",code);
        response.getWriter().print(JSON.toJSON(R.ok().data("msg","短信发送成功")));
    }

    private void loginUserByMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("短信验证");
        String username = request.getParameter("username");
        String msgcode = request.getParameter("msgcode");
        String code = request.getParameter("code");
        HttpSession session = request.getSession();
        String sesssionCode = (String) session.getAttribute("CHECKCODE_SERVER");
        String sesssionMsgCode = (String) session.getAttribute("MSG_CODE");
        PrintWriter writer = response.getWriter();
        String json = "";
        if(code.equalsIgnoreCase(sesssionCode)){
            if(msgcode.equalsIgnoreCase(sesssionMsgCode)){
                User user = userService.queryUserByUsername(username);
                if(user!=null){
                    json = JSON.toJSONString(R.ok().data("userInfo",user));
                }else {
                    json = JSON.toJSONString(JSON.toJSON(R.error().data("error","用户错误")));
                }
            }else {
                json = JSON.toJSONString(JSON.toJSON(R.error().data("error","短信验证码错误")));
            }


        }else {
            json = JSON.toJSONString(JSON.toJSON(R.error().data("error","验证码错误")));
        }
        writer.print(json);
        writer.flush();
    }

    private void searchAllWorkByWord(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String word = request.getParameter("word");
        Long userId = Long.parseLong(request.getParameter("userId"));

        List<Object> allWork =  userService.searchAllWorkByWord(word,userId);
        if (allWork == null){
            response.getWriter().print(JSON.toJSON(R.error()));
        }else {
            response.getWriter().print(JSON.toJSON(R.ok().data("allWork",allWork)));

        }

    }
    private void queryAllWorkByUserId(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String userId = request.getParameter("userId");

        List<Object> allWork =  userService.queryAllWorkByUserId2(Long.parseLong(userId));
        if (allWork == null){
            response.getWriter().print(JSON.toJSON(R.error()));
        }else {
            response.getWriter().print(JSON.toJSON(R.ok().data("allWork",allWork)));

        }

    }



    //更新用户信息
    private void updateUserById(HttpServletRequest request, HttpServletResponse response)throws IOException {
        //创建工厂类DiskFileItemFactory对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建Request对象解析器
        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        //返回文件路径
        String fileUrl = null;

        //解析Request对象
        try {
            List<FileItem> fileItems = fileUpload.parseRequest(request);

            //遍历fileItems
            Map<String ,String > map = new HashMap<>();

            for (FileItem fileItem : fileItems){
                //判断是否是普通的表单项
                if (fileItem.isFormField()){
                    //表单项的name  getName()上传的文件名
                    String fieldName = fileItem.getFieldName();
                    //表单项的value
                    String value = fileItem.getString("utf-8");//tomcat编码为iso
                    map.put(fieldName,value);

                }else {

                    String uploadFilename = fileItem.getName();//上传的文件名
                    String saveFile  = FileUploadUtil.randomFilename()+FileUploadUtil.getFileSuffix(uploadFilename);
                    fileUrl = QiniuUpload.uploadByFile(fileItem.getInputStream(), "toutiao/img/"+saveFile);

                }
            }
            User user = new User();
            user.setId(Long.parseLong(map.get("id")));
            user.setNickName(map.get("nickName"));
            user.setDescribe(map.get("describe"));
            user.setAddress(map.get("address"));
            user.setAvatar(fileUrl);

            //调用service完成保存

            int update = userService.updateUserById(user);
            if (update == 1){
                response.getWriter().print(JSON.toJSON(R.ok()));

            }else {
                response.getWriter().print(JSON.toJSON(R.error()));
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }



    }

    private void registerUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String nickname = request.getParameter("name");
        String password = request.getParameter("pass");
        String username = request.getParameter("phone");
        String email= request.getParameter("email");
        boolean bool = userService.registerUser(nickname,username,password,email);
        PrintWriter writer = response.getWriter();
        String json = "";
        if(bool){
            json = JSON.toJSONString(JSON.toJSON(R.ok()));
        }else {
            json = JSON.toJSONString(JSON.toJSON(R.error().data("error","手机号或邮箱已被注册哦")));
        }
        writer.print(json);
        writer.flush();
    }

    private void loginUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("登录");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        HttpSession session = request.getSession();
        String sesssionCode = (String) session.getAttribute("CHECKCODE_SERVER");
        PrintWriter writer = response.getWriter();
        String json = "";
        if(code.equalsIgnoreCase(sesssionCode)){
            User user = userService.loginUser(username,password);
            if(user!=null){
                json = JSON.toJSONString(R.ok().data("userInfo",user));

            }else {
                json = JSON.toJSONString(JSON.toJSON(R.error().data("error","用户名或密码错误")));
            }
        }else {
            json = JSON.toJSONString(JSON.toJSON(R.error().data("error","验证码错误")));
        }
        writer.print(json);
        writer.flush();
    }

    private void queryUserByUsername(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        User user = userService.queryUserByUsername(username);
        if(user!=null){
            response.getWriter().print(JSON.toJSON(R.ok().data("userInfo",user)));
        }

    }

    private void queryUserById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        Long Id = null;
        if(id!=null && !id.isEmpty()){
            Id = Long.parseLong(id);
        }
        User user = userService.queryUserById(Id);
        if (user == null){
            response.getWriter().print((JSON.toJSON(R.error())));
        }else {
            response.getWriter().print(JSON.toJSON(R.ok().data("userInfo",user)));

        }

    }
}
